package chapter02

import scala.annotation.tailrec

/**
 * @program lu-scala01 
 * @description: 函数递归
 * @author: zhanglu 
 * @create: 2022-03-04 15:09:00
 */
object C09_FuncRecursion {

  def main(args: Array[String]): Unit = {
    println(fact01(3))
    println(fact02(5))
  }

  /**
   * 递归
   * @param n
   * @return
   */
  def fact01(n: Int): Int = {
    if (n == 0) return 1
    fact01(n - 1) * n
  }

  /**
   * 尾递归：减少栈空间的损耗，不会过多的入栈，每次都是重新覆盖当前栈的值(Java这样写无效)
   * @param n
   * @return
   */
  def fact02(n: Int): Int = {
    @tailrec
    def loop(n: Int, currentRes: Int): Int = {
      if (n == 0) return currentRes
      loop(n - 1, currentRes * n)
    }
    loop(n, 1)
  }

}
